package com.java2104.controller;

import com.java2104.entity.Notice;
import com.java2104.entity.User;
import com.java2104.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private NoticeService noticeService;

    @RequestMapping("/list")
    @ResponseBody
    public List<Notice> list(String title,String content){
        return noticeService.getNotices(title,content);
    }

    @PostMapping("/add")
    @ResponseBody
    public Map add(String title, String content,@SessionAttribute("loginUser") User loginUser){
        Notice notice = new Notice();
        notice.setTitle(title);
        notice.setContent(content);
        notice.setCreateUser(loginUser);
        Map ret = noticeService.save(notice);
        return ret;
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Notice notice){
        noticeService.update(notice);
        return "success";
    }
    @RequestMapping("/edit/{eId}")
    public String edit(@PathVariable Integer eId, Model model) throws IOException{
        model.addAttribute("notice",noticeService.get(eId));
        return "notice/showUpdateNotice";
    }

    @RequestMapping("/preview/{eId}")
    public String preview(@PathVariable Integer eId, Model model) throws IOException{
        model.addAttribute("notice",noticeService.get(eId));
        return "notice/previewNotice";
    }

    @PostMapping(path = "/delete",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String delete(@RequestBody List<Integer> ids, HttpServletResponse response){
        int n = noticeService.delete(ids);
        response.setContentType("text/html;charset=utf-8");
        return "成功删除了" + n + "个文档";
    }
}
